package ch02.shili.shili4;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class BookDom {
    public void test() {
        //得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //从DOM工厂活得DOM解析器
        DocumentBuilder db = null;
        try {
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        //解析XML文档，得到一个Document对象，即DOM树
        Document doc = null;
        try {
            doc = db.parse("src/信息收藏.xml");
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //创建Brand节点
        Element brandElement = doc.createElement("Type");
        brandElement.setAttribute("name", "三星");
        //创建Type节点
        Element typeElement = doc.createElement("Type");
        typeElement.setAttribute("name", "NoteX");
        //添加父子关系
        brandElement.appendChild(typeElement);
        Element phoneElement = (Element) doc.getElementsByTagName("PhoneInfo").item(0);
        phoneElement.appendChild(brandElement);
        //保存XML文件
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        try {
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource domSource = new DOMSource(doc);
            //设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
            StreamResult result = new StreamResult(new FileOutputStream("src/信息收藏.xml"));
            //把DOM树转换为XML文件
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
